<?php
 /*
Plugin Name: Feed Advanced Posts (FAP)
Plugin URI: 
Description: Agarra un feed y lo transforma en posts. Usa Simplepie. Para Wordpress 2.8.5+
Version:  0.2

*/

/*  
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

//El setup del plugin, visto en http://codex.wordpress.org/Function_Reference/wp_schedule_event
register_activation_hook(__FILE__, 'rss_insert_activation');
add_action('hourly_feed_update', 'rss_insert_function');
add_action('admin_menu', 'feedposter_menu');
add_action('admin_notices', 'insertar_feed');
  
function rss_insert_activation() {
	wp_schedule_event(time(), 'hourly', 'hourly_feed_update'); 	//TODO: Pasar a opciones!
	}

//Alerta para configurar el plugin
function insertar_feed(){
	if(!get_option('fp-feed')){
	echo '<div class="error fade"><p><strong>¡Falta un feed que parsear! Debes agregarlo en la página de administración de este plugin, en la categoría de opciones</strong></p></div>';
	}
	
}

//Insertamos en el menú de administración
function feedposter_menu(){
	add_menu_page('feedposter_options', 'Feed Advanced Posts', 'administrator', __FILE__, 'feedposter_options');   
	add_action( 'admin_init', 'register_mysettings' );	
	}

function register_mysettings() {
	register_setting( 'feed-poster-group', 'fp-feed' );
	register_setting( 'feed-poster-group', 'fp-category' );
	}

//Página de opciones del plugin.
function feedposter_options(){
	
$pluginurl = plugin_basename(__FILE__);
$self = $_SERVER['PHP SELF'];

	if( isset($_POST["submit"])):
	    //remove_action('admin_notices', 'insertar_feed'); 
	    /*Creo que esta línea estaba de más, porque insertar_feed() revisa si fp-feed está vacío o no.
	    */
		$feedurl = esc_url_raw($_POST["feedurl"]);
		$feedcategory = $_POST["feedcategory"];
		update_option("fp-feed", $feedurl );
		update_option("fp-category", $feedcategory );
		wp_create_category($feedcategory); 
		rss_insert_function();
    	echo "<p><div id='message' class='updated'>
    	<p><strong>Las opciones han sido actualizadas.</strong></p>
    	</div></p>";
 	endif;
?>
<div class="wrap">
<h2>Feed Advanced Posts</h2>

<form method="post" action="<?php echo $self; ?>">
    <?php settings_fields( 'feed-poster-group' ); ?>
		<dl class="row">
			<dt>URL</dt>
			<dd>
				<input type="text" name="feedurl" value="<?php echo get_option('fp-feed'); ?>" />
			</dd>
		</dl>
		<dl class="row">
 			<dt>Categoría Asociada</dt>
			<dd>
				<input type="text" name="feedcategory" value="<?php echo get_option('fp-category'); ?>" />
			</dd>
		</dl>
    
		<div class="row">
		    <input type="submit" class="button-primary" name="submit" value="<?php _e('Save Changes') ?>" />		
		</div>

</form>
</div>
<?php 
}

 
//Ahora, lo entrete, parsear el RSS.
function rss_insert_function(){

	global $wpdb;
	 	
 	//Simplepie
	include_once(ABSPATH . WPINC . '/feed.php');
	require_once(ABSPATH . WPINC . '/class-feed.php');

    //Declarar el Feed.
    $url = get_option("fp-feed");

	$cache_location = ( TEMPLATEPATH . '/libraries/cache/' );
	$feed = new SimplePie();
	
	$feed->set_feed_url($url);
	$feed->set_cache_location($cache_location);
	$feed->set_cache_duration(0);
	$strip_htmltags = $feed->strip_htmltags;
	
	//Para no filtrar las imágenes
	unset($strip_htmltags[array_search('img', $strip_htmltags)]);
	$strip_htmltags = array_values($strip_htmltags);
	$feed->strip_htmltags($strip_htmltags);
	//e Iniciamos.
	$feed->init();
	
	//buscar el id de la categoría correspondiente. 
  	$category_id = get_cat_id(get_option("fp-category")); 
 
    //Loop entre los posts guardados con el custom meta GUID y lo hacemos un array. Papa.
 	$guid_r = array(); 
 	
 	//Reviso si existe wp_postmeta.
//	$pmetaprefix = $wpdb->prefix."postmeta";
	
 	$existing_meta = mysql_query("SELECT * FROM wp_postmeta WHERE meta_key = 'guid'") or die("<b>Error fatal</b>.\n<br />Query: " . $query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());
 	if ($existing_meta){
		while($meta_exists = mysql_fetch_array($existing_meta)){
		$guid = $meta_exists['meta_value']; 
		array_push($guid_r, $guid);
		unset($guid);
		};
	} else {
	echo "<p><div class='error fade'>
    	<p><strong>No hay Metas</strong></p>
    	</div></p>";
	};

	
	foreach ($feed->get_items(0, 0) as $item) {
	
 
 		//Si encuentra un GUID que ya existe en el array, actualiza el post.
		if(in_array($item->get_id(), $guid_r, false)){
			
			$rss_guid = $item->get_id();
			$rss_description = $item->get_content();
			
//			$update_post_id = $wpdb->get_var($wpdb->prepare("SELECT post_id FROM ".$pmetaprefix." WHERE meta_value='$rss_guid'"));		
			$update_post_id = $wpdb->get_var($wpdb->prepare("SELECT post_id FROM wp_postmeta WHERE meta_value='$rss_guid'"));		
			echo '<div class="error">';
			print_r($update_post_id);
			echo '</div>';
			$updated_info = array();
			$updated_info['ID'] = $update_post_id;
			$updated_info['post_content'] = $rss_description;
			
			wp_update_post($updated_info);
			
			unset($rss_guid);
			unset($rss_description);
			unset($update_post_id);

			break;

		} else { //Sino, hace un post nuevo.
		
			$postnew = array();
			$postnew['post_title'] = $item->get_title();
			$postnew['post_content'] = $item->get_content();
			$postnew['post_status'] = 'publish';
			$postnew['post_author'] = 1;
			$postnew['post_category'] = array($category_id);
			$postnew['post_date'] = $item->get_date('Y-m-d H:i:s');
 
			$postID = wp_insert_post($postnew);						
			add_post_meta($postID, guid, $item->get_id());			
		}
		unset($item);		
 	}
}
    
  //Para desinstalar, paramos de invocar cada hora y sacamos las opciones.  
 
register_deactivation_hook(__FILE__, 'rss_insert_deactivation');

function rss_insert_deactivation() {
	wp_clear_scheduled_hook('hourly_feed_update');
	delete_option("fp-feed");
	delete_option("fp-category");	
}

//Y sería.
?>
